﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace LookupFieldEntityPicker.Helpers
{
    public class ListHelpers
    {
        public static List<DepartmentEntity> FindDepartments(string fieldInternalName, string searchValue)
        {
            if (String.IsNullOrEmpty(fieldInternalName))
                return GetAllDepartments();


            string query = "<Where>";

            query += "<BeginsWith>";
            switch (fieldInternalName)
            {
                case Constants.DEPARTMENT_CODE:
                    query += "<FieldRef Name='" + Constants.DEPARTMENT_CODE + "'/><Value Type='Text'>" + searchValue + "</Value>";
                    break;
                case Constants.DEPARTMENT_NAME:
                    query += "<FieldRef Name='" + Constants.DEPARTMENT_NAME + "'/><Value Type='Text'>" + searchValue + "</Value>";
                    break;
                default:
                    return GetAllDepartments();
            }
           
            query += "</BeginsWith>";

            query += "</Where>";

            return FindDepartments(query);
        }


        private static List<DepartmentEntity> GetAllDepartments()
        {
            List<DepartmentEntity> resultList = new List<DepartmentEntity>();
            SPList list = SPContext.Current.Web.GetList(Constants.LOOKUP_LIST_URL);
            if (list == null)
                return resultList;

            foreach (SPListItem item in list.Items)
            {
                DepartmentEntity department = new DepartmentEntity() { ID = Int32.Parse(item["ID"].ToString()), Code = item[Constants.DEPARTMENT_CODE].ToString(), Description = item[Constants.DEPARTMENT_DESCRIPTION].ToString(), Name = item[Constants.DEPARTMENT_NAME].ToString() };
                resultList.Add(department);
            }

            return resultList;
        }


        private static List<DepartmentEntity> FindDepartments(string query)
        {

            List<DepartmentEntity> resultList = new List<DepartmentEntity>();
            SPList list = SPContext.Current.Web.GetList(Constants.LOOKUP_LIST_URL);
            if (list == null)
                return resultList;

            SPQuery q = new SPQuery();
            q.Query = query;
            SPListItemCollection result = list.GetItems(q);

            foreach (SPListItem item in result)
            {
                DepartmentEntity department = new DepartmentEntity() { ID = Int32.Parse(item["ID"].ToString()), Code = item[Constants.DEPARTMENT_CODE].ToString(), Description = item[Constants.DEPARTMENT_DESCRIPTION].ToString(), Name = item[Constants.DEPARTMENT_NAME].ToString() };
                resultList.Add(department);
            }

            return resultList;
        }
    }
}
